package com.nauu.atombuilder.actions;

import java.io.InputStream;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Platform;
import org.eclipse.gef.ui.actions.EditorPartAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;

import com.nauu.atombuilder.generator.ModelGenerator;
import com.nauu.atombuilder.modle.Diagram;

public class TemplateAction extends EditorPartAction{

	public static final String ID = "TEMPLATE_ACTION";
	
	public TemplateAction(IEditorPart editor) {
		super(editor);
		setId(ID);
	}

	@Override
	protected boolean calculateEnabled() {
		return true;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			
			IFile file = ((IFileEditorInput)getEditorPart().getEditorInput()).getFile();
			InputStream istream = file.getContents(false);
			Diagram diagram = Diagram.makeFromStream(istream);
			ModelGenerator maker = new ModelGenerator();
			maker.execute(Platform.getInstanceLocation().getURL().getFile(),file.getProject().getLocation().toString(),file.getProject().getName(),diagram.getNodes(),this.getWorkbenchPart().getSite().getShell());
		} catch (Exception e) {
			MessageDialog.openInformation(
					getEditorPart().getSite().getShell(),
					"Popupmenu",
					e.getMessage());
			e.printStackTrace();
		}
//		  try { // attempt to read from a file
//       	   System.out.println("runnnn11111111111111");
//       	   IFile file = ((IFileEditorInput)getEditorPart().getEditorInput()).getFile();
//       	   System.out.println(file.getName());
//              InputStream istream = file.getContents(false);
//              XStream xs = new XStream();
////              Diagram diagram = (Diagram)xs.fromXML(istream,new Diagram());
//              Diagram diagram = Diagram.makeFromStream(istream);
//              List<Node> list = diagram.getNodes();
//              System.out.println(diagram.getNodes().size());
//          	for (Node node : list) {
//          		System.out.println("=====================");
//  				System.out.println(node.getName()+":");
//  				System.out.println(node.getLocation().x+":"+node.getLocation().y);
//  				if(node instanceof Grid){
//  					Grid grid = (Grid)node;
//  					System.out.println(grid.getId());
//  					List<Connection> l = grid.getOutputs();
//  					for (Connection connection : l) {
//						System.out.println("target:  "+connection.getTarget().getName());
//					}
//  				}
//  				System.out.println("=====================");
//  			}
//          } catch (Exception e) { // but if there's an error, create a new diagram
//              e.printStackTrace();
//          }
	}
	
	
}